<template>
  <div class="search-suggest-temp">
    <!-- 搜索建议组件 -->
    <van-cell
      class="search-item"
      :title="item"
      v-for="(item,index) in suggestsList"
      icon="search"
      :key="index"
      @click="$emit('to-search',item)"
    >
      <!-- 点击建议，触发父组件的onsearch事件 -->
      <div slot="title" v-html="replaceKeyWord(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { getSearchSuggests } from '@/api/article'
export default {
  props: {
    searchText: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      suggestsList: []
    }
  },
  methods: {
    async loadSearchSuggests(val) {
      try {
        const { data: res } = await getSearchSuggests(val)
        console.log(res)
        this.suggestsList = res.data.options
      } catch (err) {
        console.log(err)
        this.$toast.fail('获取联想建议失败')
      }
    },
    replaceKeyWord(res) {
      // 将搜索建议中关键字高亮
      const reg = new RegExp(this.searchText, 'gi')
      return res.replace(
        reg,
        `<span class="high-light">${this.searchText}</span>`
      )
    },
    tosearch(item) {
      // 点击将此作为要搜索的项
    }
  },
  watch: {
    searchText: {
      handler: debounce(function(val) {
        this.loadSearchSuggests(val)
      }, 200),
      immediate: true
    }
  },
  computed: {}
}
</script>

<style lang='less' scoped>
.search-suggest-temp {
  .search-item {
    /deep/.high-light {
      color: rgb(149, 194, 25);
    }
  }
}
</style>
